package com.aiyige.page.publish.info;

import android.app.Activity;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.content.IntentFilter;
import android.os.AsyncTask;
import android.os.Bundle;
import android.support.v7.widget.RecyclerView;
import android.text.Editable;
import android.text.InputFilter;
import android.text.TextUtils;
import android.text.TextWatcher;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.TextView;

import com.aiyige.R;
import com.aiyige.arouter.config.ARouterConfig;
import com.aiyige.base.BaseActivity;
import com.aiyige.base.api.ApiManager;
import com.aiyige.base.api.ResponseCode;
import com.aiyige.location.LocationService;
import com.aiyige.location.LocationUtil;
import com.aiyige.location.model.LocationData;
import com.aiyige.page.interest.model.Interest;
import com.aiyige.page.interest.selectpublishinterest.SelectPublishInterestPage;
import com.aiyige.page.interest.util.InterestUtil;
import com.aiyige.page.my.settings.ConfigUltis;
import com.aiyige.page.publish.info.adapter.InterestAdapter;
import com.aiyige.page.publish.info.model.PublishInfoFormModel;
import com.aiyige.page.publish.selectinterest.PublishSelectInterestPage;
import com.aiyige.page.publish.selectinterest.model.PublishIndustryItem;
import com.aiyige.page.publish.selectinterest.model.PublishInterestItem;
import com.aiyige.page.publish.selecttag.SelectTagPage;
import com.aiyige.page.publish.tag.adapter.TagAdapter;
import com.aiyige.page.publish.tag.model.TagItem;
import com.aiyige.page.publish.util.PublishUtil;
import com.aiyige.track.TrackEvent;
import com.aiyige.track.annotation.Track;
import com.aiyige.utils.CancelEditDialogUtil;
import com.aiyige.utils.EditTextAutoMoveCursorToEndFocusChangeListener;
import com.aiyige.utils.ErrorUtil;
import com.aiyige.utils.ExcludeEmojiInputFilter;
import com.aiyige.utils.ExcludeEnterInputFilter;
import com.aiyige.utils.ExcludeSpaceInputFilter;
import com.aiyige.utils.GlideUtil;
import com.aiyige.utils.InputNumFilter;
import com.aiyige.utils.ListUtil;
import com.aiyige.utils.SafeAsyncTask;
import com.aiyige.utils.StringUtils;
import com.aiyige.utils.ToastX;
import com.aiyige.utils.dialog.LoadingDialog;
import com.aiyige.utils.widget.CommonBottomDialogFragment;
import com.aiyige.utils.widget.GprsNotificationDialogUtil;
import com.aiyige.utils.widget.articleview.ArticleView;
import com.alibaba.android.arouter.facade.annotation.Autowired;
import com.alibaba.android.arouter.facade.annotation.Route;
import com.alibaba.android.arouter.launcher.ARouter;
import com.beloo.widget.chipslayoutmanager.ChipsLayoutManager;
import com.chad.library.adapter.base.BaseQuickAdapter;
import com.luck.picture.lib.PictureSelector;
import com.luck.picture.lib.config.PictureConfig;
import com.luck.picture.lib.config.PictureMimeType;
import com.luck.picture.lib.entity.LocalMedia;
import com.vondear.rxtools.RxNetTool;

import java.util.Arrays;
import java.util.List;

import butterknife.BindView;
import butterknife.ButterKnife;
import butterknife.OnClick;
import okhttp3.ResponseBody;
import retrofit2.Response;

@Track("发布文章")
@Route(path = ARouterConfig.PublishInfoPage, extras = ARouterConfig.EXTRA_NEED_LOGIN | ARouterConfig.EXTRA_NEED_BINDPHONE)
public class PublishInfoPage extends BaseActivity {
    public static final int REQUEST_CODE_SELECT_INTEREST = 2;
    public static final int REQUEST_CODE_SELECT_TAG = 4;
    public static final int REQUEST_CODE_SELECT_COVER = 5;
    public static final int MAX_INFO_TITLE_LENGTH = 30;
    @BindView(R.id.titleBackBtn)
    ImageView titleBackBtn;
    @BindView(R.id.titleTv)
    TextView titleTv;
    @BindView(R.id.titleActionBtn)
    TextView titleActionBtn;
    @BindView(R.id.containerLayout)
    View containerLayout;
    @BindView(R.id.articleView)
    ArticleView articleView;
    @BindView(R.id.controlPanel)
    LinearLayout controlPanel;
    RecyclerView interestRv;
    BroadcastReceiver receiver;
    LocationData locationData = new LocationData();
    InputNumFilter inputNumFilter;

    //header
    View publishInfoPageHeader;
    TextView addCoverBtn;
    ImageView coverIv;
    LinearLayout changeCoverLayout;
    EditText infoTitleEt;
    ImageView infoTitleClearBtn;
    TextView interestTv;
    LinearLayout interestLayout;
    TextView locationTv;
    LinearLayout locationLayout;
    TextView inputNumTv;
    TextView maxInputNumTv;
    //footer
    View publishInfoPageFooter;
    //
    PublishInfoActionBottomDialog publishInfoActionBottomDialog;
    TrackEvent trackEvent = new TrackEvent();
    CommonBottomDialogFragment locationOptionDialog;
    @Autowired
    PublishInfoFormModel formModel = null;
    InterestAdapter interestAdapter;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.page_publish_info);
        ButterKnife.bind(this);
        ARouter.getInstance().inject(this);
        if (formModel == null) {
            ToastX.show(R.string.unknown_error);
            super.finish();
            return;
        }
        initHeader();
        initFooter();
        articleView.onCreate(this);
        switch (formModel.getOperationType()) {
            case PublishUtil.OPERATION_TYPE_EDIT:
                titleTv.setText(R.string.edit_info_title);
                break;
            case PublishUtil.OPERATION_TYPE_CREATE:
                titleTv.setText(R.string.publish_info_title);
                break;
        }
        titleActionBtn.setText(R.string.publish);
        // titleActionBtn.setEnabled(false);
        receiver = new BroadcastReceiver() {
            @Override
            public void onReceive(Context context, Intent intent) {
                try {
                    String action = intent.getAction();
                    switch (action) {
                        case LocationService.ACTION_LOCATION_FINISH:
                            locationData = intent.getParcelableExtra(LocationService.EXTRA_LOCATION_DATA);
                            if (locationData.isSuccess()) {
                                locationTv.setText(locationData.getCity());
                                updatePublishButton();
                            } else {
                                throw new Exception("定位失败");
                            }
                            break;
                    }
                } catch (Exception e) {
                    locationTv.setText(R.string.click_retry);
                    LocationUtil.showLocationFailedDialog(PublishInfoPage.this);
                }
            }
        };
        IntentFilter intentFilter = new IntentFilter();
        intentFilter.addAction(LocationService.ACTION_LOCATION_FINISH);
        registerReceiver(receiver, intentFilter);
        LocationService.startLocation(this);
        inputNumTv.setText("0");
        maxInputNumTv.setText(String.valueOf(MAX_INFO_TITLE_LENGTH));
        inputNumFilter = new InputNumFilter(MAX_INFO_TITLE_LENGTH, false);
        inputNumFilter.setListener(new InputNumFilter.Listener() {
            @Override
            public void inputNum(int num) {
                inputNumTv.setText(String.valueOf(num));
            }
        });
        infoTitleEt.setFilters(new InputFilter[]{new ExcludeEnterInputFilter(), new ExcludeEmojiInputFilter(), inputNumFilter});
        infoTitleEt.addTextChangedListener(new TextWatcher() {
            @Override
            public void beforeTextChanged(CharSequence s, int start, int count, int after) {

            }

            @Override
            public void onTextChanged(CharSequence s, int start, int before, int count) {

            }

            @Override
            public void afterTextChanged(Editable s) {
//                if (s.length() > 0) {
//                    infoTitleClearBtn.setVisibility(View.VISIBLE);
//                } else {
//                    infoTitleClearBtn.setVisibility(View.INVISIBLE);
//                }
                formModel.setTitle(s.toString());
                updatePublishButton();
            }
        });
        infoTitleEt.setOnFocusChangeListener(new View.OnFocusChangeListener() {
            @Override
            public void onFocusChange(View v, boolean hasFocus) {
                if (hasFocus) {
                    infoTitleEt.setSelection(infoTitleEt.getText().length());
                }
            }
        });
        interestAdapter = new InterestAdapter();
        interestRv.setLayoutManager(ChipsLayoutManager.newBuilder(this).build());
        interestAdapter.bindToRecyclerView(interestRv);
        interestAdapter.setOnItemClickListener(new BaseQuickAdapter.OnItemClickListener() {
            @Override
            public void onItemClick(BaseQuickAdapter adapter, View view, int position) {
                try {
                    adapter.remove(position);
                } catch (Exception e) {
                }
            }
        });

        publishInfoActionBottomDialog = PublishInfoActionBottomDialog.newInstance();
        publishInfoActionBottomDialog.setListener(new PublishInfoActionBottomDialog.Listener() {
            @Override
            public void preview() {
                if (!checkFormValidate(false)) {
                    return;
                }
                ARouter.getInstance().build(ARouterConfig.PublishInfoPreviewPage)
                        .withParcelable("formModel", formModel)
                        .navigation();
            }

            @Override
            public void finish() {
                if (!checkFormValidate(false)) {
                    return;
                }
                doPublish();
            }

            @Override
            public void cancel() {

            }
        });
        locationOptionDialog = CommonBottomDialogFragment.newBuilder()
                .layoutResId(R.layout.location_option_dialog)
                .viewIdList(Arrays.asList(R.id.deleteLocationBtn, R.id.relocationBtn, R.id.cancelBtn))
                .listener(new CommonBottomDialogFragment.Listener() {
                    @Override
                    public void onViewClicked(int position, View view) {
                        switch (view.getId()) {
                            case R.id.deleteLocationBtn:
                                locationData = new LocationData();
                                locationTv.setText(R.string.address_label);
                                break;
                            case R.id.relocationBtn:
                                LocationService.startLocation(PublishInfoPage.this, true);
                                break;
                            case R.id.cancelBtn:
                                break;
                        }
                    }
                })
                .build();
        updateView();
        articleView.setData(formModel.getArticleNodeList());
    }

    public void updateView() {
        if (!TextUtils.isEmpty(formModel.getTitle())) {
            infoTitleEt.setText(formModel.getTitle());
        } else {
            infoTitleEt.setText("");
        }

        if (!TextUtils.isEmpty(formModel.getCoverUrl())) {
            coverIv.setVisibility(View.VISIBLE);
            changeCoverLayout.setVisibility(View.VISIBLE);
            addCoverBtn.setVisibility(View.INVISIBLE);
            GlideUtil.with(this)
                    .loadCover(formModel.getCoverUrl())
                    .into(coverIv);
        } else {
            coverIv.setVisibility(View.INVISIBLE);
            changeCoverLayout.setVisibility(View.INVISIBLE);
        }

        if (!TextUtils.isEmpty(formModel.getLocationData().getCity())) {
            locationTv.setText(formModel.getLocationData().getCity());
        }
        interestAdapter.setNewData(formModel.getInterestList());
        if (!ListUtil.isEmpty(formModel.getInterestList())) {
            interestRv.setVisibility(View.VISIBLE);
        } else {
            interestRv.setVisibility(View.INVISIBLE);
        }
    }

    public void updatePublishButton() {
        // titleActionBtn.setEnabled(checkFormValidate(true));
    }

    public boolean checkFormValidate(boolean mute) {
//        if (!locationData.isSuccess()) {
//            if (!mute) ToastX.show(R.string.location_unfinished);
//            LocationService.startLocation(this);
//            return false;
//        }
//        if (ListUtil.isEmpty(tagAdapter.getData())) {
//            if (!mute) ToastX.show(R.string.please_select_tag);
//            return false;
//        }
        if (TextUtils.isEmpty(formModel.getCoverUrl())) {
            if (!mute) ToastX.show(R.string.please_select_cover);
            return false;
        }
        if (TextUtils.isEmpty(formModel.getTitle())) {
            if (!mute) ToastX.show(R.string.please_input_title);
            return false;
        }
        if (ListUtil.isEmpty(formModel.getInterestList())) {
            if (!mute) ToastX.show(R.string.please_select_interest);
            return false;
        }
        if (articleView.isEmpty()) {
            if (!mute) ToastX.show(R.string.please_input_content);
            return false;
        } else {
            formModel.setArticleNodeList(articleView.getData());
        }
        return true;
    }


    public void initHeader() {
        publishInfoPageHeader = articleView.addHeader(R.layout.publish_info_page_header);
        addCoverBtn = (TextView) publishInfoPageHeader.findViewById(R.id.addCoverBtn);
        coverIv = (ImageView) publishInfoPageHeader.findViewById(R.id.coverIv);
        changeCoverLayout = (LinearLayout) publishInfoPageHeader.findViewById(R.id.changeCoverLayout);
        infoTitleEt = (EditText) publishInfoPageHeader.findViewById(R.id.infoTitleEt);
        infoTitleClearBtn = (ImageView) publishInfoPageHeader.findViewById(R.id.infoTitleClearBtn);
        infoTitleClearBtn.setVisibility(View.INVISIBLE);
        interestTv = (TextView) publishInfoPageHeader.findViewById(R.id.interestTv);
        interestLayout = (LinearLayout) publishInfoPageHeader.findViewById(R.id.interestLayout);
        locationTv = (TextView) publishInfoPageHeader.findViewById(R.id.locationTv);
        locationLayout = (LinearLayout) publishInfoPageHeader.findViewById(R.id.locationLayout);
        interestRv = (RecyclerView) publishInfoPageHeader.findViewById(R.id.interestRv);
        inputNumTv = (TextView) publishInfoPageHeader.findViewById(R.id.inputNumTv);
        maxInputNumTv = (TextView) publishInfoPageHeader.findViewById(R.id.maxInputNumTv);
        addCoverBtn.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                PictureSelector.create(PublishInfoPage.this)
                        .openGallery(PictureMimeType.ofImage())
                        .minSelectNum(1)
                        .selectionMode(PictureConfig.SINGLE)
                        .previewImage(false)
                        .enableCrop(false)
                        .isCamera(true)
                        .compress(false)
                        .imageSpanCount(4)
                        .forResult(REQUEST_CODE_SELECT_COVER);
            }
        });
        coverIv.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                PictureSelector.create(PublishInfoPage.this)
                        .openGallery(PictureMimeType.ofImage())
                        .minSelectNum(1)
                        .selectionMode(PictureConfig.SINGLE)
                        .previewImage(false)
                        .enableCrop(false)
                        .isCamera(true)
                        .compress(false)
                        .imageSpanCount(4)
                        .forResult(REQUEST_CODE_SELECT_COVER);
            }
        });
        infoTitleClearBtn.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                infoTitleEt.setText("");
            }
        });
        interestLayout.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
//                if (formModel.getInterestList().size() >= InterestUtil.MAX_SELECTED_PUBLISH_INTEREST_NUM) {
////                    ToastX.show(StringUtils.getString(R.string.reach_max_select_interest_num_warning, InterestUtil.MAX_SELECTED_PUBLISH_INTEREST_NUM));
////                    return;
////                }
                ARouter.getInstance()
                        .build(ARouterConfig.SelectPublishInterestPage)
                        .withObject("selectedInterestList", formModel.getInterestList())
                        .withObject("publishIndustryList", formModel.getIndustryList())
                        .navigation(PublishInfoPage.this, REQUEST_CODE_SELECT_INTEREST);
            }
        });
        locationLayout.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                locationOptionDialog.show(getSupportFragmentManager(), "");
            }
        });
        infoTitleEt.setOnFocusChangeListener(new EditTextAutoMoveCursorToEndFocusChangeListener());
    }

    public void initFooter() {
        publishInfoPageFooter = articleView.addFooter(R.layout.publish_info_page_footer);
    }

    @Override
    protected void onDestroy() {
        try {
            unregisterReceiver(receiver);
        } catch (Exception e) {

        }
        articleView.onDestroy();
        super.onDestroy();
    }


    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        switch (requestCode) {
            case REQUEST_CODE_SELECT_INTEREST:
                if (resultCode == RESULT_OK) {
                    List<Interest> interestList = data.getParcelableArrayListExtra(SelectPublishInterestPage.ACTION_INTEREST_DATA);
                    List<Interest> industryList = data.getParcelableArrayListExtra(SelectPublishInterestPage.ACTION_INDUSTRY_DATA);
                    formModel.setInterestList(interestList);
                    formModel.setIndustryList(industryList);
                    updateView();
                    updatePublishButton();
                }
                break;
            case REQUEST_CODE_SELECT_COVER:
                if (resultCode == RESULT_OK) {
                    List<LocalMedia> selectList = PictureSelector.obtainMultipleResult(data);
                    if (!ListUtil.isEmpty(selectList)) {
                        LocalMedia localMedia = selectList.get(0);
                        formModel.setCoverUrl(localMedia.getPath());
                        formModel.setCoverNeedUpload(true);
                    }
                    updateView();
                    updatePublishButton();
                }
                break;
            case ArticleView.REQUEST_CODE_SELECT_PHOTO:
            case ArticleView.REQUEST_CODE_SELECT_VIDEO:
                articleView.onActivityResult(requestCode, resultCode, data);
                break;
            default:
                super.onActivityResult(requestCode, resultCode, data);
                break;
        }
    }


    @OnClick({R.id.titleBackBtn, R.id.titleActionBtn})
    public void onViewClicked(View view) {
        switch (view.getId()) {
            case R.id.titleBackBtn:
                finish();
                break;
            case R.id.titleActionBtn:
                if (checkFormValidate(false)) {
                    publishInfoActionBottomDialog.show(getSupportFragmentManager(), "");
                    // doPublish();
                }
                break;
        }
    }


    public void executePublish() {
        if (!RxNetTool.isWifi(this) && ConfigUltis.isEnableGprsNotification()) {
            GprsNotificationDialogUtil.createPublishBuilder(this)
                    .setPositiveButton(R.string.confirm_upload, new DialogInterface.OnClickListener() {
                        @Override
                        public void onClick(DialogInterface dialog, int which) {
                            int publishOperationType;
                            switch (formModel.getOperationType()) {
                                case PublishUtil.OPERATION_TYPE_CREATE:
                                    publishOperationType = PublishUtil.PUBLISH_OPERATION_TYPE_SUBMIT_REVIEW;
                                    break;
                                case PublishUtil.OPERATION_TYPE_EDIT:
                                    publishOperationType = PublishUtil.PUBLISH_OPERATION_TYPE_EDIT_SUBMIT_REIVEW;
                                    break;
                                default:
                                    publishOperationType = PublishUtil.PUBLISH_OPERATION_TYPE_SUBMIT_REVIEW;
                                    break;
                            }
                            new PublishInfoTask(PublishInfoPage.this, formModel, publishOperationType).execute();
                        }
                    })
                    .setNegativeButton(R.string.cancel, null)
                    .create()
                    .show();
        } else {
            int publishOperationType;
            switch (formModel.getOperationType()) {
                case PublishUtil.OPERATION_TYPE_CREATE:
                    publishOperationType = PublishUtil.PUBLISH_OPERATION_TYPE_SUBMIT_REVIEW;
                    break;
                case PublishUtil.OPERATION_TYPE_EDIT:
                    publishOperationType = PublishUtil.PUBLISH_OPERATION_TYPE_EDIT_SUBMIT_REIVEW;
                    break;
                default:
                    publishOperationType = PublishUtil.PUBLISH_OPERATION_TYPE_SUBMIT_REVIEW;
                    break;
            }
            new PublishInfoTask(this, formModel, publishOperationType).execute();
        }
    }

    public void doPublish() {
        new CheckSensitiveWordTask(formModel).execute();
    }

    @Override
    public void finish() {
        CancelEditDialogUtil.newbuilder(this)
                .setPositiveButton(R.string.confirm, new DialogInterface.OnClickListener() {
                    @Override
                    public void onClick(DialogInterface dialog, int which) {
                        PublishInfoPage.super.finish();
                    }
                })
                .setNegativeButton(R.string.cancel, new DialogInterface.OnClickListener() {
                    @Override
                    public void onClick(DialogInterface dialog, int which) {

                    }
                })
                .create()
                .show();
    }

    public class CheckSensitiveWordTask extends AsyncTask<Object, Object, Object> {
        LoadingDialog loadingDialog;
        PublishInfoFormModel formModel;

        public CheckSensitiveWordTask(PublishInfoFormModel formModel) {
            this.formModel = formModel;
        }

        @Override
        protected void onPreExecute() {
            loadingDialog = LoadingDialog.newBuilder()
                    .with(PublishInfoPage.this)
                    .show();
        }

        @Override
        protected Object doInBackground(Object... objects) {
            try {
                Response<ResponseBody> response = ApiManager.getService().checkSensitiveWord(PublishUtil.convertInfoFormModelToMoment(formModel)).execute();
                if (response.code() != ResponseCode.CREATED) {
                    throw new Exception(ErrorUtil.extractMessageFromErrorResponse(response));
                }
                return null;
            } catch (Exception e) {
                return e;
            }
        }

        @Override
        protected void onPostExecute(Object o) {
            loadingDialog.dismiss();
            if (o == null) {
                executePublish();
            } else if (o instanceof Exception) {
                ToastX.show(((Exception) o).getMessage());
            }
        }
    }

    public class PublishInfoTask extends SafeAsyncTask<Object, Object, Object> {
        private PublishInfoFormModel infoFormModel;
        private int publishOperationType;

        public PublishInfoTask(Activity activity, PublishInfoFormModel infoFormModel, int publishOperationType) {
            super(activity, R.string.text_process);
            this.infoFormModel = infoFormModel;
            this.publishOperationType = publishOperationType;
        }

        @Override
        protected Object doInBackground(Object... objects) {
            try {
                return PublishUtil.publishInfo(publishOperationType, infoFormModel);
            } catch (Exception e) {
                return e;
            }
        }

        @Override
        public void safeOnPostExecute(Object o) {
            if (o instanceof Exception) {
                ToastX.show(((Exception) o).getMessage());
            } else {
                ToastX.show(R.string.publishing_info);
                PublishInfoPage.super.finish();
                PublishUtil.jumpToDMPage(getActivity());
            }
        }
    }
}
